/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validators;

import entities.User;
import facades.UserFacade;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;
import util.Sha256Encrypter;

/**
 *
 * @author damfercer
 */
@Named
@RequestScoped
public class PasswordValidator implements Validator{
    @Inject
    private UserFacade userFacade;

    
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        String password=value.toString();
        Integer idUser = (Integer)component.getAttributes().get("idUser");
        User user= userFacade.find(idUser);
        try {
            password = Sha256Encrypter.getSha256(password);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(PasswordValidator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PasswordValidator.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(!password.equals(user.getPassword())){
            String errorMsg=rb.getString("IncorrectOldPassword");
            FacesMessage msg =new FacesMessage(errorMsg,errorMsg);
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
    
}
